# coding:utf-8
import json
import random
import time

from django.db.models import Q
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from core.common import ajax
from models.gg.model import YhInsideUser, User
from models.siyou.model import Clear, LiuYan, Game, UserManage, DCCOLL


def get_info(request):
    """"""
    uid = request.uid
    logs = Clear.objects.filter(uid=uid).order_by("-id").values_list("explain", flat=True)
    logs = [o for o in logs]
    ly = LiuYan.objects.filter().all().order_by("-id")
    liuyan = [dict(name=o.name,content=o.content,time = time.strftime('%m/%d %H:%M:%S', time.localtime(o.add_time))) for o in ly]

    return ajax(dict(logs=logs,liuyan=liuyan))
@csrf_exempt
def liuyan(request):
    """
    时间紧促，留言和快速添加答案合为一个接口
    """
    uid = request.uid
    username = User.objects.filter(pk=uid).last().first_name
    lx = int(request.GET.get('type','1'))
    type = int(request.GET.get('radio','1'))
    content = json.loads(request.body)
    if lx == 1:
        name = u'%s(%s)'%(username , u'学生' if type == 1 else u'老师')
        now = int(time.time())
        LiuYan.objects.create(uid=uid,name=name,content=content.get('text'),add_time=now)
    elif lx == 2:
        is_success = False
        uname = 'xs' + content.get('username')
        user = User.objects.filter(username=uname).last()
        if not user:
            message = '没有此用户'
            return ajax(message=message)
        res = YhInsideUser.objects.filter(user_id=user.id).last()
        if not res:
            YhInsideUser.objects.create(user_id=user.id,status=1)
            message = u'学生姓名:%s--处理完成！'%user.first_name
            is_success = True
        else:
            if res.status == 0:
                YhInsideUser.objects.filter(user_id=user.id).update(status=1)
                message = u'学生姓名:%s--处理完成！'%user.first_name
                is_success = True
            else:
                message = '你已经有答案了'
        if is_success:
            time1 = time.strftime('%m/%d %H:%M:%S', time.localtime(int(time.time())))
            main = u'您于%s为学生%s添加了答案----4' % (time1,user.first_name)
            Clear.objects.create(uid=uid, explain=main, type=4, add_time=int(time.time()))
        return ajax(message=message)
    return ajax()
def get_game_log(uid):
    res = Game.objects.filter(uid=uid, type=1).last()
    jilu = json.loads(res.dw) if res else []

    return jilu
def game(request):
    """"""
    ziyuan = [(u'赢', u'羸'), (u'未', u'末'), (u'暧', u'暖'), (u'肓', u'盲'), (u'夭', u'天'),(u'令',u'今')]
    level = {"1":28,"2":104,"3":252,"4":442,"5":640}
    l = request.GET.get('l','1')   # 挑战等级　传入默认一级
    try:
        n = level[l]
    except:
        n = level["5"]
    obj = random.choice(ziyuan) # 干扰项
    grx = list(obj[0] * n)
    right = obj[-1] ;m = random.randint(1, n)
    grx[m - 1] = right
    num = grx.index(right)  # 正确答案的位置

    jilu = get_game_log(request.uid)

    return ajax(dict(c=grx,n=num,al=n,l=int(l)+1,jilu=jilu))

def game_res(request):
    """"""
    dw = {"1": "☆最强王者☆", "2": "☆超凡大师☆",
          "3": "☆璀璨砖石☆", "4": "☆华贵铂金☆", "5": "●荣耀黄金●", "6": "●不屈白银●", "7": "*英勇黄铜*", "8": "*垃圾塑料*"}

    time = int(request.GET.get('time','100'))  # 时间
    l = int(request.GET.get('l','1'))
    if time <= 1:
        score = dw["1"]
    elif time <= 3:
        score = dw["2"]
    elif time <= 7:
        score = dw["3"]
    elif time <= 12:
        score = dw["4"]
    elif time <= 18:
        score = dw["5"]
    elif time <= 30:
        score = dw["6"]
    elif time <= 50:
        score = dw["7"]
    else:
        score = dw["8"]
    current = {"lv":"lv%s"%l,"dw":score,"time":time}
    res = Game.objects.filter(uid=request.uid, type=1).last()
    if not res:
        res = Game.objects.create(uid=request.uid,type=1,time=0,dw=json.dumps([]))
    data = json.loads(res.dw)
    cur = next((k for k in data if k.get('lv') == "lv%s"%l),None)
    if cur:
        if int(cur["time"] > time):
            cur["time"] = time
            cur["dw"] = score
    else:
        if l < 6:
            data.append(current)
    Game.objects.filter(uid=request.uid, type=1).update(dw=json.dumps(data))

    jilu = get_game_log(request.uid)
    return ajax(dict(score=score,time=time,jilu=jilu))

def is_have_ans(list):
    """判断拼图是否有解"""
    list.pop(-1)
    j = 1  # 从后往前轮训的数
    n = len(list)  # 列表的长度
    num = 0  # 逆序数
    for o in range(0, len(list)):
        m = list[n - 1]  # 轮训到某个数
        for i in list[:-j]:
            if i > m:
                num += 1
        j += 1
        n -= 1
        if j >= len(list):
            break
    print '逆序数', num
def get_honer(corn):
    honer = '穷鬼'
    if corn <= 2000:
        honer = '穷鬼'
    elif 2000 < corn < 5000:
        honer = '贫民'
    elif 5000 < corn < 10000:
        honer = '平民'
    elif 10000 < corn < 20000:
        honer = '富裕'
    elif 20000 < corn < 50000:
        honer = '土豪'
    elif 50000 < corn < 100000:
        honer = '神豪'
    elif 100000 < corn < 500000:
        honer = '富甲一方'
    else:
        honer = '天外飞仙'
    return honer


def get_corn(request):
    """
    获取金币数
    :param request:
    :return:
    """
    uid = request.uid
    user = User.objects.filter(pk=uid).last()
    user_corn = UserManage.objects.filter(uid=uid).last()
    user_corn = user_corn.corn
    user_name = user.first_name
    honer = get_honer(user_corn)
    return ajax(dict(name=user_name,corn=user_corn,honer=honer))
@csrf_exempt
def update_corn(request):
    """"""
    type = int(request.GET.get('type','1'))
    post = json.loads(request.body)
    uid = request.uid
    currnet_corn = UserManage.objects.filter(uid=uid).last().corn
    num = int(post.get('num', '0'))
    now = currnet_corn
    if type == 1:   # 充值金币
        if not UserManage.objects.filter(Q(uid=uid, status=1, update_time__gt=int(time.time())) | Q(uid=uid,type__gte=5)).exists():
            return ajax(status=-1,message=u'对不起，非本站超级会员不能充值，请联系郭哥')
        now = currnet_corn + num
        UserManage.objects.filter(uid=uid).update(corn = now)
    elif type == 2: # 输金币处理
        now = num
        UserManage.objects.filter(uid=uid).update(corn=num)
    elif type == 3: # 赢金币处理
        now = num
        UserManage.objects.filter(uid=uid).update(corn=now)
    elif type == 4: # 花钱
        now = now - num if now > num else 0
        UserManage.objects.filter(uid=uid).update(corn=now)
    elif type == 5:
        now = now + num
        UserManage.objects.filter(uid=uid).update(corn=now)
    honer = get_honer(now)
    user_name = User.objects.filter(pk=uid).last().first_name
    return ajax(dict(name=user_name,corn=now,honer=honer))
@csrf_exempt
def coll_dc(request):
    """收集赌场数据，便于后期统计"""
    post = json.loads(request.body)
    a1 = int(post.get('img1'))
    a2 = int(post.get('img2'))
    a3 = int(post.get('img3'))
    res = 0 # 1豹子2顺子3大4小
    if a1 == a2 == a3:
        res = 1
    elif ((a1 == a2 +1) and (a2 == a3 + 1)) or (a2 == a1 + 1 and a3 == a2 + 1):
        res = 2
    elif 12 <= a1 + a2 + a3 <= 18:
        res = 3
    elif a1 + a2 + a3 <= 9:
        res = 4
    DCCOLL.objects.create(a1=a1,a2=a2,a3=a3,res=res,uid=request.uid,sum=a1+a2+a3)
    return ajax()
def coll_g(request):
    """"""
    all = DCCOLL.objects.filter()
    res = all.count()
    if res == 0:
        res1 = res2 = res3 = res4 = res0 = 0
        data = dict(list=[res1, res3, res4, res2, res0], all=res)
        return render(request, 'dc.html', context=data)
    res1 = round(float(all.filter(res=1).count()* 100 ) / res,2)
    res2 = round(float(all.filter(res=2).count()* 100 ) / res,2)
    res3 = round(float(all.filter(res=3).count()* 100 ) / res,2)
    res4 = round(float(all.filter(res=4).count()* 100 ) / res,2)
    res0 = round(float(all.filter(res=0).count()* 100 ) / res,2)
    list2 = []
    for o in range(3,19): # 详情数据
        n = all.filter(sum=o).count()
        list2.append(n)
    #  扇形统计图数据
    list3 = {
        "value1": all.filter(res=1).count(),
        "value3": all.filter(res=3).count(),
        "value4": all.filter(res=4).count(),
        "value2": all.filter(res=2).count(),
        "value0": all.filter(res=0).count()
    }
    # data = dict(res=res,res1=res1,res2=res2,res3=res3,res4=res4,res0=res0)
    data = dict(list=[res1,res3,res4,res2,res0],all=res,list2=list2,list3=list3)
    return render(request,'dc.html',context=data)




